import React, { useState } from 'react';
import '../../style/LoginPage.css';
import { Link, useNavigate } from 'react-router-dom';
import { useGlobalContext } from '../GlobalContext';
import axios from '../../API';

const LoginPage = () => {

  const { userId, setUserId } = useGlobalContext();
  // 创建 state 来保存输入的邮箱和密码
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const getUserId = async (email) => {
    try {
      const response = await fetch(`http://localhost:8088/users/email/${email}`)
      const data = await response.json();
      if (data.code == 200) {
        setUserId(data.data.id)
        console.log(userId);

      } else {
        console.error('Failed to fetch userId:', data.message);
      }
    } catch (error) {
      console.error('Error fetching user data:', error);
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault(); // 阻止表单提交的默认行为
    try {
      const response = await axios.post('/users/login', {
        email,
        password
      });

      // 如果后端返回 code 为 200，表示登录成功
      if (response.data.code === 200) {
        getUserId(email)
        navigate('/musicapp', { state: { userId: response.data.data.id, userNickname: response.data.data.nickname } }); // 登录成功，跳转到 MusicApp 页面
      } else {
        // 后端返回的错误信息，如果没有具体的错误消息则显示默认的错误
        setError(response.data.message || '账号或者密码错误');
      }
    } catch (err) {
      // 检查错误类型
      if (err.response) {
        // 服务器返回了响应，提取错误信息
        console.error('Backend error:', err.response.data);
        setError(err.response.data.message || '发生错误，请稍后重试');
      } else if (err.request) {
        // 请求已发出，但没有收到响应
        console.error('No response received:', err.request);
        setError('网络错误，请检查连接');
      } else {
        // 其他错误
        console.error('Error in setting up request:', err.message);
        setError('请求配置错误');
      }
    }
  };

  return (
    <div className="site">
      <div className="containercon">
        <div className="Login">
          <div className="leftcon">
            <h1>Login For MusicWeb</h1>
            <h5>if you don't have an account<br />you can <Link to={"/register"}><span>Register here</span></Link></h5>
          </div>
          <div className="maincon">
            <form onSubmit={handleSubmit}>
              <p>
                <input
                  type="email"
                  placeholder="Your E-mail"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </p>
              <p className="password">
                <input
                  type="password"
                  placeholder="Your password"
                  // autocomplete="current-password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <i className="ri-eye-off-line"></i>
                <a onClick={() => setIsModalVisible(true)}>忘记密码</a>
              </p>
              {error && <p className="error">{error}</p>}  {/* 显示错误信息 */}
              <p>
                <input
                  type="submit"
                  name="submit"
                  id="loginsubmit"
                  value="Sign in"
                />
              </p>
            </form>
            <div className="options">
              <div className="separator">
                <p>or continue with</p>
              </div>
              <ul>
                <li><a href="#"><i className="ri-wechat-fill ri-2x"></i></a></li>
                <li><a href="#"><i className="ri-qq-fill ri-2x"></i></a></li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>

  );
};
export default LoginPage;
